package com.kedll.library.util;

import android.os.Handler;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 定时器
 * Created by cyt on 2015/1/11.
 */
public class MyTimer {
    private Handler handler;
    private Timer timer;
    private MyTask mTask;

    /**
     * 构造函数
     * @param handler
     */
    public MyTimer(Handler handler) {
        this();
        this.handler = handler;
    }

    public MyTimer() {
        timer = new Timer();
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    /**
     * 启动定时器,不需要延迟执行
     * @param period
     */
    public void schedule(long period) {
        schedule(0, period);
    }

    /**
     * 延迟多少时间启动定时器
     * @param delay
     * @param period
     */
    public void schedule(long delay, long period) {
        if (mTask != null) {
            mTask.cancel();
            mTask = null;
        }
        mTask = new MyTask(handler);
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(mTask, delay, period);
    }

    /**
     * 取消定时器
     */
    public void cancel() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
        if (mTask != null) {
            mTask.cancel();
            mTask = null;
        }
    }

    class MyTask extends TimerTask {
        private Handler handler;

        public MyTask(Handler handler) {
            this.handler = handler;
        }

        @Override
        public void run() {
            if (handler != null) {
                handler.obtainMessage().sendToTarget();
            }
        }

    }
}
